package com.dinadi.yidi.ui.activity;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.dinadi.yidi.R;
import com.dinadi.yidi.adapter.ImageBrowserAdapter;
import com.dinadi.yidi.utils.Constant;
import com.dinadi.yidi.utils.FileUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.BitmapCallback;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import okhttp3.Call;

/*查看相册*/
public class ShowImageFromWebActivity extends Activity implements View.OnClickListener {
    private ViewPager vpImageBrowser;
    private TextView tvImageIndex;
    private Button btnSave;
    private ImageView btn_return;
    private ImageBrowserAdapter adapter;
    private ArrayList<String> imgUrls;
    private String url;
    private int currentIndex;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_image_from_web);
        initView();
        initListener();
        initData();
    }

    private void initView() {
        vpImageBrowser = (ViewPager) findViewById(R.id.vp_image_browser);
        tvImageIndex = (TextView) findViewById(R.id.tv_image_index);
        btnSave = (Button) findViewById(R.id.btn_save);
        btn_return = (ImageView) findViewById(R.id.btn_return);
    }

    private void initData() {
        imgUrls = getIntent().getStringArrayListExtra(Constant.IMAGE_URL_ALL);
        url = getIntent().getStringExtra(Constant.IMAGE_URL);
        String sID = getIntent().getStringExtra(Constant.POSITION);
        int position;
        if (sID != null) {
            position = Integer.parseInt(sID);//String转int 
        } else {
            position = imgUrls.indexOf(url);

        }
        adapter = new ImageBrowserAdapter(this, imgUrls);
        vpImageBrowser.setAdapter(adapter);
        final int size = imgUrls.size();

        if (size > 1) {
            tvImageIndex.setVisibility(View.VISIBLE);
            tvImageIndex.setText((position + 1) + "/" + size);
        } else {
            tvImageIndex.setVisibility(View.GONE);
        }

        vpImageBrowser.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int arg0) {
                currentIndex = arg0;
                int index = arg0 % size;
                tvImageIndex.setText((index + 1) + "/" + size);

            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
                // TODO Auto-generated method stub

            }
        });

        vpImageBrowser.setCurrentItem(position);
    }

    private void initListener() {
        btnSave.setOnClickListener(this);
        btn_return.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_save:
                downloadImage();
                break;
            case R.id.btn_return:
                ShowImageFromWebActivity.this.finish();
                break;
            default:
                break;
        }
    }


    /**
     * 开始下载图片
     */
    private void downloadImage() {
//        ImageLoaderUtils.downLoadImage(imgUrls.get(currentIndex), Environment.getExternalStorageDirectory().getAbsolutePath() + "/ImagesFromWebView",ShowImageFromWebActivity.this);
        if (imgUrls.size() == 0) {
            Toast.makeText(ShowImageFromWebActivity.this, "暂无图片", Toast.LENGTH_SHORT).show();
            return;
        }
        //   Bitmap bitmap = returnBitMap(imgUrls.get(currentIndex));

        OkHttpUtils.get()
                .url(imgUrls.get(currentIndex))
                .build()
                .connTimeOut(5000)
                .readTimeOut(5000)
                .execute(new BitmapCallback() {
                    @Override
                    public void onError(Call call, Exception e) {

                    }

                    @Override
                    public void onResponse(Bitmap response) {
                        FileUtils.savePhoto(ShowImageFromWebActivity.this, response, new FileUtils.SaveResultCallback() {
                            @Override
                            public void onSavedSuccess() {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(ShowImageFromWebActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }

                            @Override
                            public void onSavedFailed() {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(ShowImageFromWebActivity.this, "保存失败", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }
                        });
                    }
                });
    }

    public Bitmap returnBitMap(String url) {
        URL myFileUrl = null;
        Bitmap bitmap = null;
        try {
            myFileUrl = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        try {
            HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }


}
